<template>
  <div class="home-index-container">
    <header>依浓集市</header>
    <div class='head'>
      <div class='head-address' @click='selectAddress'>
        <div class='iconfont icon-locationfill'></div>
        <div class='head-address-text'>{{location.title || myAddress}}</div>
      </div>
    </div>
    <Swipe :autoplay="4000" indicator-color="white" class="swipe-container">
      <SwipeItem v-for="(item, index) in bannerList" :key="index">
        <img :src="item.Image" class="slide-image" />
      </SwipeItem>
    </Swipe>
    <div class='shops-container van-shops-container'>
      <List
        class="shop-list"
        :finished="none"
        v-model="loading"
        :finished-text="finishedText"
        @load="loadMore"
      >
        <ShopItem class="shop-item" v-for="shop in shopList" :data="shop" :key="shop.Id" />
      </List>
    </div>
    <baidu-map v-if="loadMap" class="map" :center="center" :zoom="15" @ready="mapReady">
      <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-geolocation>
    </baidu-map>
    <Popup v-model="isShowRedDaily">
      <div class="red-list">
        <RedItem class="red-item" v-for="(item, index) in redList" :key="index" :data="item" />
        <a href="javascript:;" class="btn" @click="isShowRedDaily = false">我知道了</a>
      </div>
    </Popup>
  </div>
</template>
<script>
import { Swipe, SwipeItem, List, Popup } from 'vant';
import ShopItem from '@/components/ShopItem'
import { getToken } from '../../utils/auth';
import RedItem from '@/components/RedItem';
import dayjs from 'dayjs'
export default {
  components: {
    Swipe,
    SwipeItem,
    ShopItem,
    List,
    RedItem,
    Popup
  },
  data() {
    return {
      location: {},
      myAddress: '请选择当前地址',
      isSelectAddress: false,
      shopList: [],
      bannerList: [],
      none: false,
      loading: false,
      isDev: false,
      finishedText: '暂无店铺',
      center: '',
      loadMap: false,
      storeId: '',
      isShowRedDaily: false,
      redList: [],
      refreshLoading: false,
    };
  },
  methods: {
    onRefresh() {
      setTimeout(() => {
        this.refreshLoading = false;
      }, 0);
    },
    // 领取每日红包
    getRedDaily() {
      this.$http.home.getCoupon().then(({ result }) => {
        if (result.length > 0) {
          this.redList = result;
          this.isShowRedDaily = true;
          this.setRedDaily();
        }
      })
    },
    // 设置领取每日红包日期
    setRedDaily() {
      const day = dayjs().format('YYYY-MM-DD');
      window.localStorage.setItem('red-daily', day);
    },
    // 判断今日是否领取过红包
    isGetRedDaily() {
      const day = window.localStorage.getItem('red-daily');
      const now = dayjs().format('YYYY-MM-DD');
      return !!day && day === now;
    },
    selectAddress() {
      this.isSelectAddress = true;
      this.$router.push('/map/location?type=0')
    },
    mapReady({ BMap, map }) {
      this.BMap = BMap;
      this.map = map;
      const geolocation = new this.BMap.Geolocation();
      geolocation.getCurrentPosition((r) => {
        const point = r.point;
        const mk = new BMap.Marker(point);
        this.center = point;
		  	this.map.addOverlay(mk);
        this.map.centerAndZoom(point, 12);
        this.getPOI(point).then(({ surroundingPois }) => {
          const location = surroundingPois[0];
          this.$store.commit("SET_LOCATION", location);
          this.location = location;
          this.getHomeData(location.point);
        });
      }, {
        enableHighAccuracy: true,
        timeout: 10,
        maximumAge: 0
      });
    },
    getPOI(point) {
      var geocoder = new this.BMap.Geocoder();
      var locationOptions = {
        poiRadius: 1500,
        numPois: 10
      };
      var pt = point;
      return new Promise((resolve, reject) => {
        geocoder.getLocation(
          pt,
          result => {
            resolve(result);
          },
          locationOptions
        );
      });
    },
    loadMore() {
      console.log('loadmore');
    },
    getHomeData(point) {
      let longitude;
      let latitude;
      longitude = point.lng;
      latitude = point.lat;
      const { storeId } = this;
      this.$http.home.get({
        longitude,
        latitude,
        storeId
      }).then((ret) => {
        this.loading = false;
        this.none = true;
        const data = ret.result;
        this.shopList = data.Stores;
        this.finishedText = data.Stores.length === 0 ? '暂无店铺' : `您附近共有以上${data.Stores.length}家店`
        this.bannerList = data.Banners;
        if (!this.isGetRedDaily()) {
          this.getRedDaily()
        }
      })
    },
  },
  created() {
    this.isDev = this.$route.query.dev === 'true';
    this.storeId = window.sessionStorage.getItem('qr-storeid') || '';
    // window.localStorage.removeItem('Location');
    // window.localStorage.removeItem('yncarts');
    // document.cookie = '';
  },
  activated() {
    this.location = this.$store.getters.location || {};
    if (this.location.point && getToken()) {
      this.loading = true;
      this.none = false;
      this.getHomeData(this.location.point);
    } else if (!this.location.point){
      this.loadMap = true;
    }
  }
}
</script>
<style lang="less" scoped>
.home-index-container{
  header{
    height: 46PX;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 17PX;
    background-color: @maincolor;
    color: #fff;
  }
  .head {
    background: @maincolor;
    color: #fff;
    padding: 0 20px;
    height: 35PX;
    line-height: 35PX;
    .head-address {
      display: flex;
      align-items: center;
      font-size: 28px;
    }
    .head-address-text {
      margin-left: 10px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  .swipe-container{
    height: 140PX;
  }
  .slide-image{
    height: 140PX;
    width: 100%;
  }
  .shop-item{
    &:not(:last-child) {
      .border-bottom(#efefef);
    }
  }
  .red-list{
    background-color: #e51c24;
    padding: 30px 0;
    .red-item{
      background-color: #fff;
      &:not(:nth-last-child(2)) {
        .border-bottom(#dedede);
        margin-bottom: 30px;
      }
    }
    .btn{
      display: block;
      margin: 30px auto 0;
      width: 220px;
      height: 60px;
      background-color: rgba(250, 213, 122, 1);
      font-size: 26px;
      text-align: center;
      line-height: 60px;
      border-radius: 4px;
    }
  }
  .van-shops-container{
    min-height: calc(100vh - 271px);
  }
}
</style>
